package kz.kstu.website.service.impl;

import kz.kstu.website.entity.CommonEntityConstant;
import kz.kstu.website.entity.security.Account;
import kz.kstu.website.service.api.JpaUserDetailsService;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.persistence.*;

/**
 * User: Dmitry Leontyev
 * Date: 10.01.11
 * Time: 17:26
 */
@Transactional
public class JpaUserDetailsServiceImpl implements JpaUserDetailsService {

    @PersistenceContext
    private EntityManager em;

    @Inject
    private PasswordEncoder passwordEncoder;

    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
        TypedQuery<Account> query = em.createNamedQuery(CommonEntityConstant.FIND_ACCOUNT_BY_USER_NAME, Account.class);
        query.setParameter("userName", userName);
        UserDetails userDetails;
        try {
            userDetails = query.getSingleResult();
        } catch (NoResultException nre) {
            throw new UsernameNotFoundException("Пользователь с таким именем не найден.");
        }
        return userDetails;
    }

    public void changePassword(String userName, String newPassword) {
        TypedQuery<Account> query = em.createNamedQuery(CommonEntityConstant.FIND_ACCOUNT_BY_USER_NAME, Account.class);
        query.setParameter("userName", userName);
        Account account = query.getSingleResult();
        account.setPassword(passwordEncoder.encodePassword(newPassword, null));
        em.merge(account);
    }
}
